package com.example.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
public class UploadFileController {

    /**
     * 形式参数的名字需要和<input type="file" name="userPhotos"> 中的name属性一致
     * 底层实现是基于Spring MVC
     * @param userPhotos
     * @return
     */
    @PostMapping("/uploadFile")
    public String uploadFile(List<MultipartFile> userPhotos, HttpServletRequest req) {

        for (MultipartFile userPhoto : userPhotos) {
            System.out.println("用户上传的文件名是：" + userPhoto.getOriginalFilename());
            String upload = req.getServletContext().getRealPath("upload");
            File uploadFilePath = new File(upload);
            if (!uploadFilePath.exists()) {
                uploadFilePath.mkdir();
            }
            System.out.println("项目所在的真实路径是：" + uploadFilePath.getAbsolutePath());

            File file = new File(uploadFilePath, File.separator + userPhoto.getOriginalFilename());
//        将文件写入到磁盘
//            默认的文件最大占用空间是1048576 bytes，超出大小，报异常
//            在application.yml中配置上传的最大大小限制
            try {
                userPhoto.transferTo(file);
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败 fail";
            }
        }

        return "上传成功 success";
    }
}
